package spring.security.core.validatecode.service.impl;

import java.awt.image.BufferedImage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import com.google.code.kaptcha.impl.DefaultKaptcha;

import spring.security.core.properties.SecurityProperties;
import spring.security.core.validatecode.ImageCode;
import spring.security.core.validatecode.ValidateCodeCode;
import spring.security.core.validatecode.service.ValidateCodeGenerator;

public class ImageCodeGenerator implements ValidateCodeGenerator {

	@Autowired
	private DefaultKaptcha defaultKaptcha;
	
	@Autowired
	private SecurityProperties securityProperties;
	
	@Override
	public ValidateCodeCode generate(ServletWebRequest request) {
		int length = ServletRequestUtils.getIntParameter(request.getRequest(), "length", securityProperties.getCode().getImage().getLength());
		try {
			// 生产验证码字符串并保存到session中
			String createText = defaultKaptcha.createText();
			// 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
			BufferedImage challenge = defaultKaptcha.createImage(createText);
			return new ImageCode(challenge, createText, 10);
		} catch (Exception e) {
			return null;
		}
	}

	public SecurityProperties getSecurityProperties() {
		return securityProperties;
	}

	public void setSecurityProperties(SecurityProperties securityProperties) {
		this.securityProperties = securityProperties;
	}

}
